import Vue from 'vue'
import Vuex from 'vuex'
import { cookie } from 'vux'

Vue.use(Vuex)

var state = {
  userInfo: null
}

const mutations = {
  setUserInfo (state, userInfo) { // 处理状态(数据)变化
    state.userInfo = JSON.stringify(userInfo)
     // 写入cookie值
    cookie.set('userInfo', JSON.stringify(userInfo), {expires: 300})
  },
  removeUserInfo (state) {
    state.userInfo = null
    cookie.remove('userInfo')
  }
}

const actions = {
  setUserInfo: ({ // 处理你要干什么，异步请求，判断，流程控制
    commit,
    state
  }, userInfo
  ) => {
    commit('setUserInfo', userInfo)
  },
  removeUserInfo: ({ // 处理你要干什么，异步请求，判断，流程控制
    commit,
    state
  }
  ) => {
    commit('removeUserInfo')
  }
}

const getters = {
  getUserInfo (state) {
    // 如果为空的话那么就从cookie里面读取
    if (!state.userInfo) {
      // 读取cookie
      let cookieValue = cookie.get('userInfo')
      if (cookieValue) {
        state.userInfo = cookieValue
      }
    }
    if (state.userInfo) {
      return JSON.parse(state.userInfo)
    }
    return null
  }
}

// 需要导出Store对象
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
